/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 30318
 * Date: 2023-12-22
 * Time: 17:55
 */
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat;
import java.util.Scanner;

public class TestOfMember {
    private Member member;

    public TestOfMember() {
        member = new Member();
    }

    public Member getMember() {
        return member;
    }

    public void addMember() {//添加会员
        Scanner input = new Scanner(System.in);
        while(true) {
            //建立会员信息
            int memberID = (int)(Math.random() * 10000);//会员号码
            DecimalFormat decimalFormat = new DecimalFormat("0000");//位数不够添0
            String memberId = decimalFormat.format(memberID);
            //检测生成的会员号是否已经存在
            while(queryMember(memberId)) {
                memberID = (int)(Math.random() * 10000);
                memberId = decimalFormat.format(memberID);
            }

            System.out.println("请输入您的生日：（格式为：2000.01.01）");
            String memberbirth = input.next();//会员生日
            int points = 0;//会员积分

            //将会员信息存入文档
            try {
                File file = new File("memberInfo.txt");
                if(!file.exists()){
                    file.createNewFile();
                }
                FileWriter fileWriter = new FileWriter(file.getName(), true);
                fileWriter.write(memberId + "\t" + memberbirth + "\t" + points + "\n");
                fileWriter.close();
            } catch(IOException e){
                e.printStackTrace();
            }

            System.out.println("恭喜您，注册会员成功。");
            System.out.println("您的会员号为：" + memberId);
            System.out.println("您的生日为：" + memberbirth);
            System.out.println("您当前积分为：" + points);

            System.out.println("是否继续录入用户信息？（Y/N）");
            String isContinue = input.next();
            if (isContinue.equalsIgnoreCase("N")) {
                break;
            } else if (isContinue.equalsIgnoreCase("Y")) {
                continue;
            } else {
                System.out.println("输入有误，请重新输入。");
                continue;
            }
        }
    }

    public void displayOfMenber() {//显示所有会员
        System.out.println("*************   会员信息显示   ************");
        try (BufferedReader br = new BufferedReader(new FileReader("memberInfo.txt"))) {//读取文本中的所有会员
            String line;
            System.out.println("会员ID\t\t会员生日\t\t\t会员积分");
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\t");
                member.setMemberId(Integer.parseInt(parts[0]));
                member.setMemberBirth(parts[1]);
                member.setMemberIntegral(Integer.parseInt(parts[2]));
                System.out.println(member.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("***********   会员信息显示结束   ***********");
    }

    public boolean queryMember(String memberId) {//查询会员号
        // 读取文本文件并判断会员号
        boolean found = false;//是否找到会员号
        try (BufferedReader br = new BufferedReader(new FileReader("memberInfo.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\t");
                if (parts.length > 0 && Integer.parseInt(parts[0]) == Integer.parseInt(memberId)) {
                    found = true;
                    member.setMemberId(Integer.parseInt(parts[0]));//会员号
                    member.setMemberBirth(parts[1]);//会员生日
                    member.setMemberIntegral(Integer.parseInt(parts[2]));//会员积分
                    System.out.println("会员ID\t\t会员生日\t\t\t会员积分");
                    System.out.println(member.toString());
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return found;
    }

    public String toString() {//返回字符串
        return member.getMemberId() + "\t" + member.getMemberBirth() + "\t" + member.getMemberIntegral();
    }

    public void modify(String oldStr,String newStr) {//修改文件中的信息
        try {
            Path path = Paths.get("memberInfo.txt");
            String content = new String(Files.readAllBytes(path));
            String modifiedContent = content.replace(oldStr, newStr);
            Files.write(path,modifiedContent.getBytes(), StandardOpenOption.WRITE);
            System.out.println("会员信息修改成功！");
        } catch (IOException e) {
            System.out.println("修改文件时出错" + e.getMessage());
        }
    }

    private static boolean hasMemberInfo = true; // 全局变量，用于记录是否还有剩余的会员信息

    public void deleteMember() {
        System.out.println("*************   会员信息删除   *************");
        Scanner input = new Scanner(System.in);

        boolean continueProgram = true;

        while (continueProgram && hasMemberInfo) {
            boolean validMemberId = false;

            while (!validMemberId) {
                // 输入删除会员信息的会员号
                System.out.println("请输入要删除的会员的会员号：");
                String memberIdToDelete = input.next();
                // 删除会员信息
                boolean deleteResult = deleteMember(memberIdToDelete);
                // 根据删除结果判断是否继续循环
                if (deleteResult && !hasMemberInfo) {
                    continueProgram = false;
                    System.out.println("所有会员信息都已删除，无法继续删除");
                    break;
                } else {
                    System.out.println("是否继续删除会员信息？(Y/N)");
                    String continueDeleteOption = input.next();
                    if (continueDeleteOption.equalsIgnoreCase("N")) {
                        validMemberId = true; // 退出循环
                        continueProgram = false; // 结束程序
                    } else if (continueDeleteOption.equalsIgnoreCase("Y")) {
                        validMemberId = false;
                    } else {
                        System.out.println("无效的选项，请输入正确的信息");
                        validMemberId = true;
                    }
                }
            }
        }

        System.out.println("*************   信息删除完成   *************");
    }

    public boolean deleteMember(String memberIdToDelete) {
        try {
            File inputFile = new File("memberInfo.txt");
            File tempFile = new File("tempMemberInfo.txt");

            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

            boolean memberFound = false;

            String currentLine;

            while ((currentLine = reader.readLine()) != null) {
                String[] data = currentLine.split("\t");

                if (data.length > 0) {
                    if (data[0].equals(memberIdToDelete)) {
                        memberFound = true;
                        continue;
                    }
                }

                writer.write(currentLine + "\n");
            }
            reader.close();
            writer.close();

            if (!memberFound) {
                System.out.println("此文档中没有这个会员");
                return false;
            }
            System.out.println("会员信息删除成功");
            if (inputFile.delete()) {
                if (!tempFile.renameTo(inputFile)) {
                    System.out.println("Could not rename the file");
                }
            } else {
                System.out.println("Could not delete the file");
            }
            BufferedReader readerCheck = new BufferedReader(new FileReader(inputFile));
            if (readerCheck.readLine() == null) {
                hasMemberInfo = false;
            }
            readerCheck.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

class Member{
    private int memberId;
    private int memberIntegral;
    private String memberBirth;

    public Member() {

    }

    public Member(int memberId, int memberIntegral, String memberBrith) {
        this.memberId = memberId;
        this.memberIntegral = memberIntegral;
        this.memberBirth = memberBrith;
    }

    public int getMemberId() {
        return memberId;
    }

    public void setMemberId(int memberId) {
        this.memberId = memberId;
    }

    public int getMemberIntegral() {
        return memberIntegral;
    }

    public void setMemberIntegral(int memberIntegral) {
        this.memberIntegral = memberIntegral;
    }

    public String getMemberBirth() {
        return memberBirth;
    }

    public void setMemberBirth(String memberBrith) {
        this.memberBirth = memberBrith;
    }

    public String toString() {
        DecimalFormat decimalFormat = new DecimalFormat("0000");//位数不够添0
        String memberId = decimalFormat.format(getMemberId());
        return memberId + "\t\t" + getMemberBirth() + "\t\t" + getMemberIntegral();
    }
}